package main

import (
	"flag"
	"gim/db"
	"gim/comm"
	log "github.com/golang/glog"
	"net/http"
	"encoding/json"
	"time"
	"fmt"
	"strconv"
	"io"
)

var (
	manager *db.Manager
)

//注册新用户
func RegisterUser(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	
	uid, err := strconv.Atoi(r.PostFormValue("uid"))
	if err != nil {
		retJson(w, r, -1, "参数错误", nil)
		return
	}
	
	//判断用户存不存在
	user := manager.GetUser(comm.APP_ID, int64(uid))
	if user != nil {
		retJson(w, r, -1, "用户已经存在", nil)
		return
	}

	username := r.PostFormValue("username")
	avatar := r.PostFormValue("avatar")
	token := r.PostFormValue("token")
	
	if manager.SaveUser(comm.APP_ID, int64(uid), username, avatar, token) {
		retJson(w, r, 0, "OK", nil)
	} else {
		retJson(w, r, -1, "注册用户失败", nil)
	}
}

//获取用户
func GetUser(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	
	uid, err := strconv.Atoi(r.Form.Get("uid"))
	if err != nil {
		retJson(w, r, -1, "参数错误", nil)
		return
	}
	
	//判断用户存不存在
	user := manager.GetUser(comm.APP_ID, int64(uid))
	if user == nil {
		retJson(w, r, -1, "用户不存在", nil)
		return
	}

	data := make(map[string]string)
	data["uid"] = fmt.Sprintf("%d", user.Uid)
	data["username"] = user.Username
	data["avatar"] = user.Avatar
	data["token"] = user.Token
	
	retJson(w, r, 0, "OK", data)
}

//获取用户登录信息
func GetUserLogins(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	
	uid, err := strconv.Atoi(r.Form.Get("uid"))
	if err != nil {
		retJson(w, r, -1, "参数错误", nil)
		return
	}
	
	points, _ := manager.GetUserLoginPoints(comm.APP_ID, int64(uid))
	if points == nil {
		retJson(w, r, 0, "OK", nil)
		return
	}
	
	data := make([]map[string]string, 0, 5)
	for _, point := range points {
		p := make(map[string]string)
		p["device_id"] = point.Device_id
		p["platform_id"] = fmt.Sprintf("%d", point.Platform_id)
		p["login_srv"] = point.Login_srv
		p["login_time"] = fmt.Sprintf("%d", point.Login_time)
		
		data = append(data, p)
	}
	
	retJson(w, r, 0, "OK", data)
}

func retJson(w http.ResponseWriter, r *http.Request, retCode int, retMsg string, retData interface{}) {
	res := map[string]interface{}{
		"retCode": retCode,
		"retMsg":  retMsg,
		"retData": retData,
	}
	retWrite(w, r, res, "", time.Now())
}

//json数据输出到客户端
func retWrite(w http.ResponseWriter, r *http.Request, res map[string]interface{}, callback string, start time.Time) {
	data, err := json.Marshal(res)
	if err != nil {
		log.Errorf("json.Marshal(\"%v\") error(%v)", res, err)
		return
	}
	dataStr := ""
	if callback == "" {
		// Normal json
		dataStr = string(data)
	} else {
		// Jsonp
		dataStr = fmt.Sprintf("%s(%s)", callback, string(data))
	}
	
	if n, err := io.WriteString(w, dataStr); err != nil {
		log.Errorf("w.Write(\"%s\") error(%v)", dataStr, err)
	} else {
		log.Infof("w.Write(\"%s\") write %d bytes", dataStr, n)
	}
	log.Infof("req: \"%s\", res:\"%s\", ip:\"%s\", time:\"%fs\"", r.URL.String(), dataStr, r.RemoteAddr, time.Now().Sub(start).Seconds())
}

func main() {
	s := flag.String("-S", "127.0.0.1:8990", "127.0.0.1:8990")
	dbh := flag.String("-DBH", "127.0.0.1:6379", "127.0.0.1:6379")
	dbp := flag.String("-DBP", "", "")
	
	flag.Parse()
	
	manager = db.NewManager(*dbh, *dbp)

	http.HandleFunc("/register_user", RegisterUser)
	http.HandleFunc("/get_user", GetUser)
	http.HandleFunc("/get_userlogins", GetUserLogins)
	
	err := http.ListenAndServe(*s, nil)
	if err != nil {
		log.Error("api server err", err)
	}
}